home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Gigarom 1
/
Gigarom Macintosh Archives (Quantum Leap)(CDRM1080320)(1993).iso
/
FILES
/
DEV
/
A-B
/
002. TESample.cpt
/
TESample.c
< prev
next >
Wrap
Text File
|
1988-08-01
|
44KB
|
1,394 lines
/*------------------------------------------------------------------------------
#
# Apple Macintosh Developer Technical Support
#
# MultiFinder-Aware Simple TextEdit Sample Application
#
# TESample
#
# This file: TESample.c - C Source
#
# Copyright © 1988 Apple Computer, Inc.
# All rights reserved.
#
# Versions: 1.0 8/88
#
# Components: TESample.p August 1, 1988
# TESample.c August 1, 1988
# TESample.a August 1, 1988
# TESample.r August 1, 1988
# TESample.h August 1, 1988
# PTESample.make August 1, 1988
# CTESample.make August 1, 1988
#
# TESample is an example application that demonstrates how
# to initialize the commonly used toolbox managers, operate
# successfully under MultiFinder, handle desk accessories and
# create, grow, and zoom windows. The fundamental TextEdit
# toolbox calls and TextEdit autoscroll are demonstrated. It
# also shows how to create and maintain scrollbar controls.
#
# It does not by any means demonstrate all the techniques you
# need for a large application. In particular, Sample does not
# cover exception handling, multiple windows/documents,
# sophisticated memory management, printing, or undo. All of
# these are vital parts of a normal full-sized application.
#
# This application is an example of the form of a Macintosh
# application; it is NOT a template. It is NOT intended to be
# used as a foundation for the next world-class, best-selling,
# 600K application. A stick figure drawing of the human body may
# be a good example of the form for a painting, but that does not
# mean it should be used as the basis for the next Mona Lisa.
#
# We recommend that you review this program or Sample before
# beginning a new application. Sample is a simple app. which doesn’t
# use TextEdit or the Control Manager.
#
------------------------------------------------------------------------------*/
/* Segmentation strategy:
This program consists of three segments. Main contains most of the code,
including the MPW libraries, and the main program. Initialize contains
code that is only used once, during startup, and can be unloaded after the
program starts. %A5Init is automatically created by the Linker to initialize
globals for the MPW libraries and is unloaded right away. */
/* SetPort strategy:
Toolbox routines do not change the current port. In spite of this, in this
program we use a strategy of calling SetPort whenever we want to draw or
make calls which depend on the current port. This makes us less vulnerable
to bugs in other software which might alter the current port (such as the
bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
Hopefully, this also makes the routines from this program more self-contained,
since they don't depend on the current port setting. */
/* Clipboard strategy:
This program does not maintain a private scrap. Whenever a cut, copy, or paste
occurs, we import/export from the public scrap to TextEdit's scrap right away,
using the TEToScrap and TEFromScrap routines. If we did use a private scrap,
the import/export would be in the activate/deactivate event and suspend/resume
event routines. */
#include <Values.h>
#include <Types.h>
#include <QuickDraw.h>
#include <Fonts.h>
#include <Events.h>
#include <Controls.h>
#include <Windows.h>
#include <Menus.h>
#include <TextEdit.h>
#include <Dialogs.h>
#include <Desk.h>
#include <Scrap.h>
#include <ToolUtils.h>
#include <Memory.h>
#include <SegLoad.h>
#include <Files.h>
#include <OSUtils.h>
#include <Traps.h> /* MPW 2.0.2 Traps.h is missing an #endif */
#include <TESample.h> /* bring in all the #defines for Sample */
/* A DocumentRecord contains the WindowRecord for one of our document windows,
as well as the TEHandle for the text we are editing. Other document fields
can be added to this record as needed. For a similar example, see how the
Window Manager and Dialog Manager add fields after the GrafPort. */
typedef struct {
WindowRecord docWindow;
TEHandle docTE;
ControlHandle docVScroll;
ControlHandle docHScroll;
ProcPtr docClik;
} DocumentRecord, *DocumentPeek;
/* The "g" prefix is used to emphasize that a variable is global. */
/* GMac is used to hold the result of a SysEnvirons call. This makes
it convenient for any routine to check the environment. */
SysEnvRec gMac; /* set up by Initialize */
/* GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
trap is available. If it is false, we know that we must call GetNextEvent. */
Boolean gHasWaitNextEvent; /* set up by Initialize */
/* GInBackground is maintained by our osEvent handling routines. Any part of
the program can check it to find out if it is currently in the background. */
Boolean gInBackground; /* maintained by Initialize and DoEvent */
/* GNumDocuments is used to keep track of how many open documents there are
at any time. It is maintained by the routines that open and close documents. */
short gNumDocuments; /* maintained by Initialize, DoNew, and DoCloseWindow */
/* Here are declarations for all of the C routines. In MPW 3.0 we can use
actual prototypes for parameter type checking. */
#ifndef MPW3
void EventLoop();
void DoEvent( /* EventRecord *event */ );
void AdjustCursor( /* Point mouse, RgnHandle region */ );
void DoGrowWindow( /* WindowPtr window, EventRecord *event */ );
void DoZoomWindow( /* WindowPtr window, short part */ );
void ResizeWindow( /* WindowPtr window */ );
void GetLocalUpdateRgn( /* WindowPtr window, RgnHandle localRgn */ );
void DoUpdate( /* WindowPtr window */ );
void DoDeactivate( /* WindowPtr window */ );
void DoActivate( /* WindowPtr window, Boolean becomingActive */ );
void DoContentClick( /* WindowPtr window, EventRecord *event */ );
void DoKeyDown( /* EventRecord *event */ );
unsigned long GetSleep();
void CommonAction( /* ControlHandle control, short *amount */ );
pascal void VActionProc( /* ControlHandle control, short part */ );
pascal void HActionProc( /* ControlHandle control, short part */ );
void DoIdle();
void DrawWindow( /* WindowPtr window */ );
void AdjustMenus();
void DoMenuCommand( /* long menuResult */ );
void DoNew();
void DoCloseWindow( /* WindowPtr window */ );
void DoCloseBehind( /* WindowPtr window */ );
void Terminate();
void Initialize();
void ForceEnvirons();
void GetTERect( /* WindowPtr window, Rect *teRect */ );
void AdjustViewRect( /* TEHandle docTE */ );
void AdjustTE( /* WindowPtr window */ );
void AdjustHV( /* Boolean isVert, ControlHandle control, TEHandle docTE,
Boolean canRedraw */ );
void AdjustScrollValues( /* WindowPtr window, Boolean canRedraw */ );
void AdjustScrollSizes( /* WindowPtr window */ );
void AdjustScrollbars( /* WindowPtr window, Boolean needsResize */ );
pascal void PascalClikLoop();
pascal ProcPtr GetOldClikLoop();
Boolean IsAppWindow( /* WindowPtr window */ );
Boolean IsDAWindow( /* WindowPtr window */ );
Boolean TrapAvailable( /* short tNumber, TrapType tType */ );
#else
void EventLoop( void );
void DoEvent( EventRecord *event );
void AdjustCursor( Point mouse, RgnHandle region );
void DoGrowWindow( WindowPtr window, EventRecord *event );
void DoZoomWindow( WindowPtr window, short part );
void ResizeWindow( WindowPtr window );
void GetLocalUpdateRgn( WindowPtr window, RgnHandle localRgn );
void DoUpdate( WindowPtr window );
void DoDeactivate( WindowPtr window );
void DoActivate( WindowPtr window, Boolean becomingActive );
void DoContentClick( WindowPtr window, EventRecord *event );
void DoKeyDown( EventRecord *event );
unsigned long GetSleep( void );
void CommonAction( ControlHandle control, short *amount );
pascal void VActionProc( ControlHandle control, short part );
pascal void HActionProc( ControlHandle control, short part );
void DoIdle( void );
void DrawWindow( WindowPtr window );
void AdjustMenus( void );
void DoMenuCommand( long menuResult );
void DoNew( void );
void DoCloseWindow( WindowPtr window );
void DoCloseBehind( WindowPtr window );
void Terminate( void );
void Initialize( void );
void ForceEnvirons( void );
void GetTERect( WindowPtr window, Rect *teRect );
void AdjustViewRect( TEHandle docTE );
void AdjustTE( WindowPtr window );
void AdjustHV( Boolean isVert, ControlHandle control, TEHandle docTE,
Boolean canRedraw );
void AdjustScrollValues( WindowPtr window, Boolean canRedraw );
void AdjustScrollSizes( WindowPtr window );
void AdjustScrollbars( WindowPtr window, Boolean needsResize );
pascal void PascalClikLoop();
pascal ProcPtr GetOldClikLoop();
Boolean IsAppWindow( WindowPtr window );
Boolean IsDAWindow( WindowPtr window );
Boolean TrapAvailable( short tNumber, TrapType tType );
#endif
/* Make the 2.0 Interface for passing Points to the Toolbox by address,
emulate the 3.0 method of passing Points by value. This list only contains
the affected routines actually used in this sample, and is not intended to
be a comprehensive list of the affected routines.
For routines that have Str255 formal parameters we cannot do a similar trick
so the necessary changes are in the code itself. Searching for MPW3 will find
them. */
#ifndef MPW3
# define FindWindow FINDWINDOW
# define MenuSelect MENUSELECT
# define DragWindow DRAGWINDOW
# define TrackGoAway TRACKGOAWAY
# define PtInRgn PTINRGN
# define TEClick TECLICK
# define FindControl FINDCONTROL
# define TrackControl TRACKCONTROL
# define GrowWindow GROWWINDOW
# define TrackBox TRACKBOX
pascal void Debugger()
extern 0xA9FF;
#endif
/* Define HiWrd and LoWrd macros for efficiency. */
#define HiWrd(aLong) (((aLong) >> 16) & 0xFFFF)
#define LoWrd(aLong) ((aLong) & 0xFFFF)
/* Define TopLeft and BotRight macros for convenience. Notice the implicit
dependency on the ordering of fields within a Rect */
#define TopLeft(aRect) (* (Point *) &(aRect).top)
#define BotRight(aRect) (* (Point *) &(aRect).bottom)
/* This routine is part of the MPW runtime library. This external
reference to it is done so that we can unload its segment, %A5Init. */
extern void _DataInit();
/* A reference to our assembly language routine that gets attached to the clikLoop
field of our TE record. */
extern pascal void AsmClikLoop();
#define __SEG__ Main
main()
{
UnloadSeg((Ptr) _DataInit); /* note that _DataInit must not be in Main! */
ForceEnvirons(); /* check for some basic requirements; exits if not met */
MaxApplZone(); /* expand the heap so code segments load at the top */
Initialize(); /* initialize the program */
UnloadSeg((Ptr) Initialize); /* note that Initialize must not be in Main! */
EventLoop(); /* call the main event loop */
}
/* Get events forever, and handle them by calling DoEvent.
Also call AdjustCursor each time through the loop. */
#define __SEG__ Main
void EventLoop()
{
RgnHandle cursorRgn;
Boolean gotEvent;
EventRecord event;
cursorRgn = NewRgn(); /* we’ll pass WNE an empty region the 1st time thru */
do {
/* use WNE if it is available */
if ( gHasWaitNextEvent )
gotEvent = WaitNextEvent(everyEvent, &event, GetSleep(), cursorRgn);
else {
SystemTask();
gotEvent = GetNextEvent(everyEvent, &event);
}
if ( gotEvent ) {
/* make sure we have the right cursor before handling the event */
AdjustCursor(event.where, cursorRgn);
DoEvent(&event);
}
else
DoIdle(); /* perform idle tasks when it’s not our event */
/* change the cursor (and region) if necessary */
AdjustCursor(event.where, cursorRgn);
} while ( true ); /* loop forever; we quit via ExitToShell */
} /*EventLoop*/
/* Do the right thing for an event. Determine what kind of event it is, and call
the appropriate routines. */
#define __SEG__ Main
void DoEvent(event)
EventRecord *event;
{
short part;
WindowPtr window;
char key;
switch ( event->what ) {
case nullEvent:
/* we idle for null/mouse moved events ands for events which aren’t
ours (see EventLoop) */
DoIdle();
break;
case mouseDown:
part = FindWindow(event->where, &window);
switch ( part ) {
case inMenuBar: /* process a mouse menu command (if any) */
AdjustMenus(); /* bring ’em up-to-date */
DoMenuCommand(MenuSelect(event->where));
break;
case inSysWindow: /* let the system handle the mouseDown */
SystemClick(event, window);
break;
case inContent:
if ( window != FrontWindow() ) {
SelectWindow(window);
/*DoEvent(event);*/ /* use this line for "do first click" */
} else
DoContentClick(window, event);
break;
case inDrag: /* pass screenBits.bounds to get all gDevices */
DragWindow(window, event->where, &qd.screenBits.bounds);
break;
case inGoAway:
if ( TrackGoAway(window, event->where) )
DoCloseWindow(window);
break;
case inGrow:
DoGrowWindow(window, event);
break;
case inZoomIn:
case inZoomOut:
if ( TrackBox(window, event->where, part) )
DoZoomWindow(window, part);
break;
}
break;
case keyDown:
case autoKey: /* check for menukey equivalents */
key = event->message & charCodeMask;
if ( event->modifiers & cmdKey ) { /* Command key down */
if ( event->what == keyDown ) {
AdjustMenus(); /* enable/disable/check menu items properly */
DoMenuCommand(MenuKey(key));
}
} else
DoKeyDown(event);
break;
case activateEvt:
DoActivate((WindowPtr) event->message, (event->modifiers & activeFlag) != 0);
break;
case updateEvt:
DoUpdate((WindowPtr) event->message);
break;
case osEvent:
switch (event->message >> 24) { /* high byte of message */
case mouseMovedMessage:
DoIdle(); /* mouse-moved is also an idle event */
break;
case suspendResumeMessage: /* suspend/resume is also an activate/deactivate */
gInBackground = (event->message & resumeMask) == 0;
DoActivate(FrontWindow(), !gInBackground);
break;
}
break;
}
} /*DoEvent*/
/* Change the cursor's shape, depending on its position. This also calculates the region
where the current cursor resides (for WaitNextEvent). When the mouse moves outside of
this region, an event is generated. If there is more to the event than just
“the mouse moved”, we get called before the event is processed to make sure
the cursor is the right one. In any (ahem) event, this is called again before we
fall back into WNE. */
#define __SEG__ Main
void AdjustCursor(mouse,region)
Point mouse;
RgnHandle region;
{
WindowPtr window;
RgnHandle arrowRgn;
RgnHandle iBeamRgn;
Rect iBeamRect;
window = FrontWindow(); /* we only adjust the cursor when we are in front */
if ( (! gInBackground) && (! IsDAWindow(window)) ) {
/* calculate regions for different cursor shapes */
arrowRgn = NewRgn();
iBeamRgn = NewRgn();
/* start arrowRgn wide open */
SetRectRgn(arrowRgn, extremeNeg, extremeNeg, extremePos, extremePos);
/* calculate iBeamRgn */
if ( IsAppWindow(window) ) {
iBeamRect = (*((DocumentPeek) window)->docTE)->viewRect;
SetPort(window); /* make a global version of the viewRect */
LocalToGlobal(&TopLeft(iBeamRect));
LocalToGlobal(&BotRight(iBeamRect));
RectRgn(iBeamRgn, &iBeamRect);
/* we temporarily change the port’s origin to “globalfy” the visRgn */
SetOrigin(-window->portBits.bounds.left, -window->portBits.bounds.top);
SectRgn(iBeamRgn, window->visRgn, iBeamRgn);
SetOrigin(0, 0);
}
/* subtract other regions from arrowRgn */
DiffRgn(arrowRgn, iBeamRgn, arrowRgn);
/* change the cursor and the region parameter */
if ( PtInRgn(mouse, iBeamRgn) ) {
SetCursor(*GetCursor(iBeamCursor));
CopyRgn(iBeamRgn, region);
} else {
SetCursor(&qd.arrow);
CopyRgn(arrowRgn, region);
}
DisposeRgn(arrowRgn);
DisposeRgn(iBeamRgn);
}
} /*AdjustCursor*/
/* Called when a mouseDown occurs in the grow box of an active window. In
order to eliminate any 'flicker', we want to invalidate only what is
necessary. Since ResizeWindow invalidates the whole portRect, we save
the old TE viewRect, intersect it with the new TE viewRect, and
remove the result from the update region. However, we must make sure
that any old update region that might have been around gets put back. */
#define __SEG__ Main
void DoGrowWindow(window,event)
WindowPtr window;
EventRecord *event;
{
long growResult;
Rect tempRect;
RgnHandle tempRgn;
Boolean ignoreResult;
DocumentPeek doc;
tempRect = qd.screenBits.bounds; /* set up limiting values */
tempRect.left = minDocDim;
tempRect.top = minDocDim;
growResult = GrowWindow(window, event->where, &tempRect);
/* see if it really changed size */
if ( growResult != 0 ) {
doc = (DocumentPeek) window;
tempRect = (*doc->docTE)->viewRect; /* save old text box */
tempRgn = NewRgn();
GetLocalUpdateRgn(window, tempRgn); /* get localized update region */
SizeWindow(window, LoWrd(growResult), HiWrd(growResult), true);
ResizeWindow(window);
/* calculate & validate the region that hasn’t changed so it won’t get redrawn */
ignoreResult = SectRect(&tempRect, &(*doc->docTE)->viewRect, &tempRect);
ValidRect(&tempRect); /* take it out of update */
InvalRgn(tempRgn); /* put back any prior update */
DisposeRgn(tempRgn);
}
} /* DoGrowWindow */
/* Called when a mouseClick occurs in the zoom box of an active window.
Everything has to get re-drawn here, so we don't mind that
ResizeWindow invalidates the whole portRect. */
#define __SEG__ Main
void DoZoomWindow(window,part)
WindowPtr window;
short part;
{
EraseRect(&window->portRect);
ZoomWindow(window, part, window == FrontWindow());
ResizeWindow(window);
} /* DoZoomWindow */
/* Called when the window has been resized to fix up the controls and content. */
#define __SEG__ Main
void ResizeWindow(window)
WindowPtr window;
{
AdjustScrollbars(window, true);
AdjustTE(window);
InvalRect(&window->portRect);
} /* ResizeWindow */
/* Returns the update region in local coordinates */
#define __SEG__ Main
void GetLocalUpdateRgn(window,localRgn)
WindowPtr window;
RgnHandle localRgn;
{
CopyRgn(((WindowPeek) window)->updateRgn, localRgn); /* save old update region */
OffsetRgn(localRgn, window->portBits.bounds.left, window->portBits.bounds.top);
} /* GetLocalUpdateRgn */
/* This is called when an update event is received for a window.
It calls DrawWindow to draw the contents of an application window.
As an efficiency measure that does not have to be followed, it
calls the drawing routine only if the visRgn is non-empty. This
will handle situations where calculations for drawing or drawing
itself is very time-consuming. */
#define __SEG__ Main
void DoUpdate(window)
WindowPtr window;
{
if ( IsAppWindow(window) ) {
BeginUpdate(window); /* this sets up the visRgn */
if ( ! EmptyRgn(window->visRgn) ) /* draw if updating needs to be done */
DrawWindow(window);
EndUpdate(window);
}
} /*DoUpdate*/
/* This is called when a window is activated or deactivated.
It calls TextEdit to deal with the selection. */
#define __SEG__ Main
void DoActivate(window, becomingActive)
WindowPtr window;
Boolean becomingActive;
{
RgnHandle tempRgn;
RgnHandle clipRgn;
DocumentPeek doc;
if ( IsAppWindow(window) ) {
doc = (DocumentPeek) window;
if ( becomingActive ) {
/* since we don’t want TEActivate to draw a selection in an area where
we’re going to erase and redraw, we’ll clip out the update region
before calling it. */
tempRgn = NewRgn();
clipRgn = NewRgn();
GetLocalUpdateRgn(window, tempRgn); /* get localized update region */
GetClip(clipRgn);
DiffRgn(clipRgn, tempRgn, tempRgn); /* subtract updateRgn from clipRgn */
SetClip(tempRgn);
TEActivate(doc->docTE);
SetClip(clipRgn); /* restore the full-blown clipRgn */
DisposeRgn(tempRgn);
DisposeRgn(clipRgn);
/* the controls must be redrawn on activation: */
(*doc->docVScroll)->contrlVis = controlVisible;
(*doc->docHScroll)->contrlVis = controlVisible;
InvalRect(&(*doc->docVScroll)->contrlRect);
InvalRect(&(*doc->docHScroll)->contrlRect);
}
else {
TEDeactivate(doc->docTE);
/* the controls must be hidden on deactivation: */
HideControl(doc->docVScroll);
HideControl(doc->docHScroll);
}
}
} /*DoActivate*/
/* This is called when a mouseDown occurs in the content of a window. */
#define __SEG__ Main
void DoContentClick(window,event)
WindowPtr window;
EventRecord *event;
{
Point mouse;
ControlHandle control;
short part, value;
Boolean shiftDown;
DocumentPeek doc;
if ( IsAppWindow(window) ) {
SetPort(window);
mouse = event->where; /* get the click position */
GlobalToLocal(&mouse);
part = FindControl(mouse, window, &control);
doc = (DocumentPeek) window;
switch ( part ) {
case 0: /* not in a control*/
/* see if we need to extend the selection */
shiftDown = (event->modifiers & shiftKey) != 0; /* extend if Shift is down */
TEClick(mouse, shiftDown, doc->docTE);
break;
case inThumb:
value = GetCtlValue(control);
part = TrackControl(control, mouse, nil);
if ( part != 0 ) {
value -= GetCtlValue(control);
/* value now has CHANGE in value; if value changed, scroll */
if ( value != 0 )
if ( control == doc->docVScroll )
TEScroll(0, value * (*doc->docTE)->lineHeight, doc->docTE);
else
TEScroll(value, 0, doc->docTE);
}
break;
default: /* they clicked in an arrow, so track & scroll */
if ( control == doc->docVScroll )
value = TrackControl(control, mouse, (ProcPtr) VActionProc);
else
value = TrackControl(control, mouse, (ProcPtr) HActionProc);
break;
}
}
} /*DoContentClick*/
/* This is called for any keyDown or autoKey events, except when the
Command key is held down. It looks at the frontmost window to decide what
to do with the key typed. */
#define __SEG__ Main
void DoKeyDown(event)
EventRecord *event;
{
WindowPtr window;
char key;
TEHandle te;
window = FrontWindow();
if ( IsAppWindow(window) ) {
te = ((DocumentPeek) window)->docTE;
key = event->message & charCodeMask;
/* we have a char. for our window; see if we are still below TextEdit’s
limit for the number of characters */
if ( (*te)->teLength - ((*te)->selEnd - (*te)->selStart) + 1 <
maxTELength ) {
TEKey(key, te);
AdjustScrollbars(window, false);
AdjustTE(window);
} else
SysBeep(8);
}
} /*DoKeyDown*/
/* Calculate a sleep value for WaitNextEvent. This takes into account the things
that DoIdle does with idle time. */
#define __SEG__ Main
unsigned long GetSleep()
{
long sleep;
WindowPtr window;
TEHandle te;
sleep = MAXLONG; /* default value for sleep */
if ( !gInBackground ) {
window = FrontWindow(); /* and the front window is ours... */
if ( IsAppWindow(window) ) {
te = ((DocumentPeek) (window))->docTE; /* and the selection is an insertion point... */
if ( (*te)->selStart == (*te)->selEnd )
sleep = GetCaretTime(); /* blink time for the insertion point */
}
}
return sleep;
} /*GetSleep*/
/* Common algorithm for pinning the value of a control. It returns the actual amount
the value of the control changed. Note the pinning is done for the sake of returning
the amount the control value changed. */
#define __SEG__ Main
void CommonAction(control,amount)
ControlHandle control;
short *amount;
{
short value, max;
value = GetCtlValue(control); /* get current value */
max = GetCtlMax(control); /* and maximum value */
*amount = value - *amount;
if ( *amount < 0 )
*amount = 0;
else if ( *amount > max )
*amount = max;
SetCtlValue(control, *amount);
*amount = value - *amount; /* calculate the real change */
} /* CommonAction */
/* Determines how much to change the value of the vertical scrollbar by and how
much to scroll the TE record. */
#define __SEG__ Main
pascal void VActionProc(control,part)
ControlHandle control;
short part;
{
short amount;
WindowPtr window;
TEPtr te;
if ( part != 0 ) { /* if it was actually in the control */
window = (*control)->contrlOwner;
te = *((DocumentPeek) window)->docTE;
switch ( part ) {
case inUpButton:
case inDownButton: /* one line */
amount = 1;
break;
case inPageUp: /* one page */
case inPageDown:
amount = (te->viewRect.bottom - te->viewRect.top) / te->lineHeight;
break;
}
if ( (part == inDownButton) || (part == inPageDown) )
amount = -amount; /* reverse direction for a downer */
CommonAction(control, &amount);
if ( amount != 0 )
TEScroll(0, amount * te->lineHeight, ((DocumentPeek) window)->docTE);
}
} /* VActionProc */
/* Determines how much to change the value of the horizontal scrollbar by and how
much to scroll the TE record. */
#define __SEG__ Main
pascal void HActionProc(control,part)
ControlHandle control;
short part;
{
short amount;
WindowPtr window;
TEPtr te;
if ( part != 0 ) {
window = (*control)->contrlOwner;
te = *((DocumentPeek) window)->docTE;
switch ( part ) {
case inUpButton:
case inDownButton: /* a few pixels */
amount = buttonScroll;
break;
case inPageUp: /* a page */
case inPageDown:
amount = te->viewRect.right - te->viewRect.left;
break;
}
if ( (part == inDownButton) || (part == inPageDown) )
amount = -amount; /* reverse direction */
CommonAction(control, &amount);
if ( amount != 0 )
TEScroll(amount, 0, ((DocumentPeek) window)->docTE);
}
} /* VActionProc */
/* This is called whenever we get a null event et al.
It takes care of necessary periodic actions. For this program, it calls TEIdle. */
#define __SEG__ Main
void DoIdle()
{
WindowPtr window;
window = FrontWindow();
if ( IsAppWindow(window) )
TEIdle(((DocumentPeek) window)->docTE);
} /*DoIdle*/
/* Draw the contents of an application window. */
#define __SEG__ Main
void DrawWindow(window)
WindowPtr window;
{
SetPort(window);
EraseRect(&window->portRect);
DrawControls(window);
DrawGrowIcon(window);
TEUpdate(&window->portRect, ((DocumentPeek) window)->docTE);
} /*DrawWindow*/
/* Enable and disable menus based on the current state.
The user can only select enabled menu items. We set up all the menu items
before calling MenuSelect or MenuKey, since these are the only times that
a menu item can be selected. Note that MenuSelect is also the only time
the user will see menu items. This approach to deciding what enable/
disable state a menu item has the advantage of concentrating all
the decision-making in one routine, as opposed to being spread throughout
the application. Other application designs may take a different approach
that is just as valid. */
#define __SEG__ Main
void AdjustMenus()
{
WindowPtr window;
MenuHandle menu;
long offset;
Boolean undo;
Boolean cutCopyClear;
Boolean paste;
TEHandle te;
window = FrontWindow();
menu = GetMHandle(mFile);
if ( gNumDocuments < maxOpenDocuments )
EnableItem(menu, iNew); /* New is enabled when we can open more documents */
else
DisableItem(menu, iNew);
if ( window != nil ) /* Close is enabled when there is a window to close */
EnableItem(menu, iClose);
else
DisableItem(menu, iClose);
menu = GetMHandle(mEdit);
undo = false;
cutCopyClear = false;
paste = false;
if ( IsDAWindow(window) ) {
undo = true; /* all editing is enabled for DA windows */
cutCopyClear = true;
paste = true;
} else if ( IsAppWindow(window) ) {
te = ((DocumentPeek) window)->docTE;
if ( (*te)->selStart < (*te)->selEnd )
cutCopyClear = true;
/* Cut, Copy, and Clear is enabled for app. windows with selections */
if ( GetScrap(nil, 'TEXT', &offset) )
paste = true; /* if there’s any text in the clipboard, paste is enabled */
}
if ( undo )
EnableItem(menu, iUndo);
else
DisableItem(menu, iUndo);
if ( cutCopyClear ) {
EnableItem(menu, iCut);
EnableItem(menu, iCopy);
EnableItem(menu, iClear);
} else {
DisableItem(menu, iCut);
DisableItem(menu, iCopy);
DisableItem(menu, iClear);
}
if ( paste )
EnableItem(menu, iPaste);
else
DisableItem(menu, iPaste);
} /*AdjustMenus*/
/* This is called when an item is chosen from the menu bar (after calling
MenuSelect or MenuKey). I It performs the right operation for each command.
It is good to have both the result of MenuSelect and MenuKey go to
one routine like this to keep everything organized. */
#define __SEG__ Main
void DoMenuCommand(menuResult)
long menuResult;
{
short menuID; /* the resource ID of the selected menu */
short menuItem; /* the item number of the selected menu */
short itemHit;
Str255 daName;
short daRefNum;
OSErr ignoreResult;
TEHandle te;
WindowPtr window;
window = FrontWindow();
menuID = HiWord(menuResult); /* use macros for efficiency to... */
menuItem = LoWord(menuResult); /* get menu item number and menu number */
switch ( menuID ) {
case mApple:
switch ( menuItem ) {
case iAbout: /* bring up alert for About */
itemHit = Alert(rAboutAlert, nil);
break;
default: /* all non-About items in this menu are DAs et al */
# ifndef MPW3
/* type Str255 is a struct in MPW 2 */
GETITEM(GetMHandle(mApple), menuItem, &daName);
daRefNum = OPENDESKACC(&daName);
# else
/* type Str255 is an array in MPW 3 */
GetItem(GetMHandle(mApple), menuItem, daName);
daRefNum = OpenDeskAcc(daName);
# endif
break;
}
break;
case mFile:
switch ( menuItem ) {
case iNew:
DoNew();
break;
case iClose:
DoCloseWindow(FrontWindow());
break;
case iQuit:
Terminate();
break;
}
break;
case mEdit: /* call SystemEdit for DA editing & MultiFinder */
if ( !SystemEdit(menuItem-1) ) {
te = ((DocumentPeek) FrontWindow())->docTE;
switch ( menuItem ) {
case iCut:
if ( ZeroScrap() == noErr ) {
TECut(te); /* after cutting, export the TE scrap */
if ( TEToScrap() != noErr ) {
SetCursor(&qd.arrow);
/* alert user if we couldn’t cut */
itemHit = Alert(rEditAlert, nil);
ignoreResult = ZeroScrap();
}
}
break;
case iCopy:
if ( ZeroScrap() == noErr ) {
TECopy(te); /* after copying, export the TE scrap */
if ( TEToScrap() != noErr ) {
SetCursor(&qd.arrow);
/* alert user if we couldn’t copy */
itemHit = Alert(rEditAlert, nil);
ignoreResult = ZeroScrap();
}
}
break;
case iPaste: /* import the TE scrap before pasting */
if ( TEFromScrap() == noErr )
if ( TEGetScrapLen() + ((*te)->teLength -
((*te)->selEnd - (*te)->selStart)) < maxTELength )
TEPaste(te);
else {
SetCursor(&qd.arrow);
/* alert user if this would exceed the limit for chars */
itemHit = Alert(rEditAlert, nil);
}
break;
case iClear:
TEDelete(te);
break;
}
AdjustScrollbars(window, false);
AdjustTE(window);
}
break;
}
HiliteMenu(0); /* unhighlight what MenuSelect (or MenuKey) hilited */
} /*DoMenuCommand*/
/* Create a new document and window. */
#define __SEG__ Main
void DoNew()
{
Boolean good;
Ptr storage;
WindowPtr window;
Rect destRect, viewRect;
DocumentPeek doc;
storage = NewPtr(sizeof(DocumentRecord));
if ( storage != nil ) {
window = GetNewWindow(rDocWindow, storage, (WindowPtr) -1);
if ( window != nil ) {
gNumDocuments += 1; /* this will be decremented when we call DoCloseWindow */
good = false;
SetPort(window);
doc = (DocumentPeek) window;
GetTERect(window, &viewRect);
destRect = viewRect;
destRect.right = destRect.left + maxDocWidth;
doc->docTE = TENew(&destRect, &viewRect);
AdjustViewRect(doc->docTE);
TEAutoView(true, doc->docTE);
doc->docClik = (ProcPtr) (*doc->docTE)->clikLoop;
#ifndef MPW3
(*doc->docTE)->clikLoop = (ProcPtr) AsmClikLoop;
#else
(*doc->docTE)->clikLoop = (ClikLoopProcPtr) AsmClikLoop;
#endif
good = doc->docTE != nil; /* if TENew succeeded, we have a good document */
if ( good ) { /* good document? — get scrollbars */
doc->docVScroll = GetNewControl(rVScroll, window);
good = (doc->docVScroll != nil);
}
if ( good) {
doc->docHScroll = GetNewControl(rHScroll, window);
good = (doc->docHScroll != nil);
}
if ( good ) { /* good? — adjust & draw the controls, draw the window */
/* false to AdjustScrollValues means musn’t redraw; technically, of course,
the window is hidden so it wouldn’t matter whether we called ShowControl or not. */
AdjustScrollValues(window, false);
ShowWindow(window);
} else {
DoCloseWindow(window); /* otherwise regret we ever created it... */
SysBeep(8); /* and beep (8 is an arbitrary duration) */
}
} else
DisposPtr(storage); /* get rid of the storage if it is never used */
}
} /*DoNew*/
/* Close a window. This handles desk accessory and application windows. */
#define __SEG__ Main
void DoCloseWindow(window)
WindowPtr window;
{
TEHandle te;
if ( IsDAWindow(window) )
CloseDeskAcc(((WindowPeek) window)->windowKind);
else if ( IsAppWindow(window) ) {
te = ((DocumentPeek) window)->docTE;
if ( te != nil )
TEDispose(te); /* dispose the TEHandle if we got far enough to make one */
DisposeWindow(window);
gNumDocuments -= 1;
}
} /*DoCloseWindow*/
/* Close the window that is passed and all windows behind it.
This closes windows from back to front, by calling itself
recursively, which minimizes window updating. Always keep
in mind the dangers of stack overflow when recursive routines
are used in situations where the calling level gets too
deep. That is not a problem here. */
#define __SEG__ Main
void DoCloseBehind(window)
WindowPtr window;
{
if ( window != nil ) { /* if we are passed a window, close other windows behind it first */
DoCloseBehind((WindowPtr) (((WindowPeek) window)->nextWindow));
DoCloseWindow(window); /* now that all the windows behind are closed, close this one */
}
} /*DoCloseBehind*/
/* Clean up the application and exits. We close all of the windows so that
they can update their documents, if any. */
#define __SEG__ Main
void Terminate()
{
DoCloseBehind(FrontWindow()); /* close all windows */
ExitToShell();
} /*Terminate*/
/* Set up the whole world, including global variables, Toolbox managers,
menus, and a single blank document. */
#define __SEG__ Initialize
void Initialize()
{
Handle menuBar;
gHasWaitNextEvent = TrapAvailable(_WaitNextEvent, ToolTrap);
gInBackground = false;
InitGraf((Ptr) &qd.thePort);
InitFonts();
InitWindows();
InitMenus();
TEInit();
InitDialogs(nil);
InitCursor();
menuBar = GetNewMBar(rMenuBar); /* read menus into menu bar */
if ( menuBar == nil ) ExitToShell();
SetMenuBar(menuBar); /* install menus */
DisposHandle(menuBar);
AddResMenu(GetMHandle(mApple), 'DRVR'); /* add DA names to Apple menu */
DrawMenuBar();
gNumDocuments = 0;
/* do other initialization here */
DoNew(); /* create a single empty document */
} /*Initialize*/
/* Make sure that the machine has at least 128K ROMs and enough memory to run.
If it doesn't, exit. SysEnvirons can be called before the toolbox managers
are initialized, and we need to call it at this point so we can check for
the right ROMs and memory availability before we call MaxApplZone and
initialize the toolbox managers. If AppleTalk has not been initialized, you
won't get the version of the AppleTalk driver that is running. That is not
critical here, and if that information was required, SysEnvirons could be
called again after AppleTalk had been initialized. */
#define __SEG__ Main
void ForceEnvirons()
{
OSErr ignoreError;
/* ignore the error returned from SysEnvirons; even if an error occurred,
the SysEnvirons glue will fill in the SysEnvRec */
ignoreError = SysEnvirons(sysEnvironsVersion, &gMac);
if ( (gMac.machineType < 0) ||
(StackSpace() + (long) GetApplLimit() - (long) ApplicZone() < kMinSize * 1024) )
ExitToShell();
/* if you have stack requirements that differ from the default,
then you could use SetApplLimit to increase StackSpace at this point. */
} /* ForceEnvirons */
/* Return a rectangle that is inset from the portRect by the size of
the scrollbars and a little extra margin. */
#define __SEG__ Main
void GetTERect(window,teRect)
WindowPtr window;
Rect *teRect;
{
*teRect = window->portRect;
InsetRect(teRect, textMargin, textMargin); /* adjust for margin */
teRect->bottom = teRect->bottom - 15; /* and for the scrollbars */
teRect->right = teRect->right - 15;
} /*GetTERect*/
/* Update the TERec's view rect so that it is the greatest multiple of
the lineHeight that still fits in the old viewRect. */
#define __SEG__ Main
void AdjustViewRect(docTE)
TEHandle docTE;
{
TEPtr te;
te = *docTE;
te->viewRect.bottom = (((te->viewRect.bottom - te->viewRect.top) / te->lineHeight)
* te->lineHeight) + te->viewRect.top;
} /*AdjustViewRect*/
/* Scroll the TERec around to match up to the potentially updated scrollbar
values. This is really useful when the window has been resized such that the
scrollbars became inactive but the TERec was already scrolled. */
#define __SEG__ Main
void AdjustTE(window)
WindowPtr window;
{
TEPtr te;
te = *((DocumentPeek)window)->docTE;
TEScroll((te->viewRect.left - te->destRect.left) -
GetCtlValue(((DocumentPeek)window)->docHScroll),
(te->viewRect.top - te->destRect.top) -
(GetCtlValue(((DocumentPeek)window)->docVScroll) *
te->lineHeight),
((DocumentPeek)window)->docTE);
} /*AdjustTE*/
/* Calculate the new control maximum value and current value, whether it is the horizontal or
vertical scrollbar. The vertical max is calculated by comparing the number of lines to the
vertical size of the viewRect. The horizontal max is calculated by comparing the maximum document
width to the width of the viewRect. The current values are set by comparing the offset between
the view and destination rects. If necessary and we canRedraw, have the control be re-drawn by
calling ShowControl. */
#define __SEG__ Main
void AdjustHV(isVert,control,docTE,canRedraw)
Boolean isVert;
ControlHandle control;
TEHandle docTE;
Boolean canRedraw;
{
short value, lines, max;
short oldValue, oldMax;
TEPtr te;
oldValue = GetCtlValue(control);
oldMax = GetCtlMax(control);
te = *docTE; /* point to TERec for convenience */
if ( isVert ) {
lines = te->nLines;
/* since nLines isn’t right if the last character is a return, check for that case */
if ( *(*te->hText + te->teLength - 1) == crCharacter )
lines += 1;
max = lines - ((te->viewRect.bottom - te->viewRect.top) /
te->lineHeight);
} else
max = maxDocWidth - (te->viewRect.right - te->viewRect.left);
if ( max < 0 ) max = 0;
SetCtlMax(control, max);
/* Must deref. after SetCtlMax since, technically, it could draw and therefore move
memory. This is why we don’t just do it once at the beginning. */
te = *docTE;
if ( isVert )
value = (te->viewRect.top - te->destRect.top) / te->lineHeight;
else
value = te->viewRect.left - te->destRect.left;
if ( value < 0 ) value = 0;
else if ( value > max ) value = max;
SetCtlValue(control, value);
/* now redraw the control if it needs to be and can be */
if ( canRedraw || (max != oldMax) || (value != oldValue) )
ShowControl(control);
} /*AdjustHV*/
/* Simply call the common adjust routine for the vertical and horizontal scrollbars. */
#define __SEG__ Main
void AdjustScrollValues(window,canRedraw)
WindowPtr window;
Boolean canRedraw;
{
DocumentPeek doc;
doc = (DocumentPeek)window;
AdjustHV(true, doc->docVScroll, doc->docTE, canRedraw);
AdjustHV(false, doc->docHScroll, doc->docTE, canRedraw);
} /*AdjustScrollValues*/
/* Re-calculate the position and size of the viewRect and the scrollbars. */
#define __SEG__ Main
void AdjustScrollSizes(window)
WindowPtr window;
{
Rect teRect;
DocumentPeek doc;
doc = (DocumentPeek) window;
GetTERect(window, &teRect);
(*doc->docTE)->viewRect = teRect;
AdjustViewRect(doc->docTE);
MoveControl(doc->docVScroll, window->portRect.right - scrollbarAdjust, -1);
SizeControl(doc->docVScroll, scrollbarWidth, window->portRect.bottom -
window->portRect.top - growboxAdjust);
MoveControl(doc->docHScroll, -1, window->portRect.bottom - scrollbarAdjust);
SizeControl(doc->docHScroll, window->portRect.right -
window->portRect.left - growboxAdjust, scrollbarWidth);
} /*AdjustScrollSizes*/
/* Turn off the controls by jamming a zero into their contrlVis fields (HideControl erases them
and we don't want that). If the controls are to be resized as well, call the procedure to do that,
then call the procedure to adjust the maximum and current values. Finally re-enable the controls
by jamming a $FF in their contrlVis fields. */
#define __SEG__ Main
void AdjustScrollbars(window,needsResize)
WindowPtr window;
Boolean needsResize;
{
DocumentPeek doc;
doc = (DocumentPeek) window;
/* First, turn visibility of scrollbars off so we won’t get unwanted redrawing */
(*doc->docVScroll)->contrlVis = controlInvisible; /* turn them off */
(*doc->docHScroll)->contrlVis = controlInvisible;
if ( needsResize ) /* move & size as needed */
AdjustScrollSizes(window);
AdjustScrollValues(window, needsResize); /* fool with max and current value */
/* Now, restore visibility in case we never had to ShowControl during adjustment */
(*doc->docVScroll)->contrlVis = controlVisible; /* turn them on */
(*doc->docHScroll)->contrlVis = controlVisible;
} /* AdjustScrollbars */
/* Gets called from our assembly language routine, AsmClikLoop, which is in
turn called by the TEClick toolbox routine. Saves the windows clip region,
sets it to the portRect, adjusts the scrollbar values to match the TE scroll
amount, then restores the clip region. */
#define __SEG__ Main
pascal void PascalClikLoop()
{
WindowPtr window;
RgnHandle region;
window = FrontWindow();
region = NewRgn();
GetClip(region); /* save clip */
ClipRect(&window->portRect);
AdjustScrollValues(window, true); /* pass true for canRedraw */
SetClip(region); /* restore clip */
DisposeRgn(region);
} /* PascalClikLoop */
/* Gets called from our assembly language routine, AsmClikLoop, which is in
turn called by the TEClick toolbox routine. It returns the address of the
default clikLoop routine that was put into the TERec by TEAutoView to
AsmClikLoop so that it can call it. */
#define __SEG__ Main
pascal ProcPtr GetOldClikLoop()
{
return ((DocumentPeek)FrontWindow())->docClik;
} /* GetOldClikLoop */
/* Check to see if a window belongs to the application. If the window pointer
passed was NIL, then it could not be an application window. WindowKinds
that are negative belong to the system and windowKinds less than userKind
are reserved by Apple except for windowKinds equal to dialogKind, which
mean it is a dialog. */
#define __SEG__ Main
Boolean IsAppWindow(window)
WindowPtr window;
{
short windowKind;
if ( window == nil )
return false;
else { /* application windows have windowKinds >= userKind (8) or dialogKind (2) */
windowKind = ((WindowPeek) window)->windowKind;
return (windowKind >= userKind) || (windowKind == dialogKind);
}
} /*IsAppWindow*/
/* Check to see if a window belongs to a desk accessory. */
#define __SEG__ Main
Boolean IsDAWindow(window)
WindowPtr window;
{
if ( window == nil )
return false;
else /* DA windows have negative windowKinds */
return ((WindowPeek) window)->windowKind < 0;
} /*IsDAWindow*/
/* Check to see if a given trap is implemented. This is only used by the
Initialize routine in this program, so we put it in the Initialize segment.
The recommended approach to see if a trap is implemented is to see if
the address of the trap routine is the same as the address of the
Unimplemented trap. */
#define __SEG__ Initialize
Boolean TrapAvailable(tNumber,tType)
short tNumber;
TrapType tType;
{
/* Check and see if the trap exists. On 64K ROM machines, tType will be ignored. */
return NGetTrapAddress(tNumber, tType) != GetTrapAddress(_Unimplemented);
} /*TrapAvailable*/